# 生成赛程（仅管理员可见）
from flask import Blueprint, render_template, request, redirect, url_for, flash, jsonify
from app.controllers.monthly_competition_controller import MonthlyCompetitionController
from app.forms.monthly_competition_forms import MonthlyCompetitionForm, MonthlyCompetitionSignupForm
from flask_login import login_required, current_user
from datetime import datetime, date, timedelta

from app.decorators import student_required, role_required
from app.controllers.reservation_controller import ReservationController
from app.forms.reservation_forms import (
    CreateReservationForm, EditReservationForm, CancelReservationForm,
    TimeSlotForm, ReservationFilterForm
)

# 创建学员预约蓝图
student_reservations_bp = Blueprint('student_reservations', __name__)


@student_reservations_bp.route('/monthly_competitions/<int:comp_id>/generate_schedule', methods=['POST'])
@login_required
@role_required('super_admin', 'campus_admin')
def generate_competition_schedule(comp_id):
    from app.services.monthly_competition_schedule_generator import MonthlyCompetitionScheduleGenerator
    for group in ['A', 'B', 'C']:
        MonthlyCompetitionScheduleGenerator.generate_schedule(comp_id, group)
    flash('赛程已生成！', 'success')
    return redirect(url_for('student_reservations.monthly_competition_detail', comp_id=comp_id))




# 月度比赛相关路由
@student_reservations_bp.route('/monthly_competitions')
@login_required
@role_required('student', 'super_admin', 'campus_admin')
def monthly_competitions():
    """
    月度比赛列表
    """
    competitions = MonthlyCompetitionController.list_competitions()
    return render_template('student_reservations/monthly_competitions.html', competitions=competitions)


# 查看学员自己的比赛顺序及球台编号
@student_reservations_bp.route('/monthly_competitions/<int:comp_id>/my_matches')
@login_required
@role_required('student')
def my_competition_matches(comp_id):
    from app.models.monthly_competition_match import MonthlyCompetitionMatch
    matches = MonthlyCompetitionMatch.query.filter_by(competition_id=comp_id, player_a_id=current_user.id).all()
    matches += MonthlyCompetitionMatch.query.filter_by(competition_id=comp_id, player_b_id=current_user.id).all()
    matches = sorted(matches, key=lambda m: (m.group, m.subgroup or 0, m.round))
    return render_template('student_reservations/my_competition_matches.html', matches=matches)
# -*- coding: utf-8 -*-
"""
学员预约视图

包含学员预约管理的所有页面和API：
- 创建预约
- 预约列表
- 预约详情
- 修改预约
- 取消预约
- 日历视图
"""



@student_reservations_bp.route('/monthly_competitions/<int:comp_id>')
@login_required
@role_required('student', 'super_admin', 'campus_admin')
def monthly_competition_detail(comp_id):
    """
    月度比赛详情
    """
    comp = MonthlyCompetitionController.get_competition(comp_id)
    signups = MonthlyCompetitionController.get_signups(comp_id)
    signup_form = MonthlyCompetitionSignupForm()
    return render_template('student_reservations/monthly_competition_detail.html', competition=comp, signups=signups, signup_form=signup_form)


@student_reservations_bp.route('/monthly_competitions/<int:comp_id>/signup', methods=['POST'])
@login_required
@role_required('student')
def monthly_competition_signup(comp_id):
    """
    学员报名月度比赛
    """
    form = MonthlyCompetitionSignupForm()
    group = form.group.data if form.validate_on_submit() else request.form.get('group')
    success, msg = MonthlyCompetitionController.signup_student(comp_id, current_user.id, group)
    flash(msg, 'success' if success else 'error')
    return redirect(url_for('student_reservations.monthly_competition_detail', comp_id=comp_id))


@student_reservations_bp.route('/monthly_competitions/create', methods=['GET', 'POST'])
@login_required
@role_required('super_admin', 'campus_admin')
def create_monthly_competition():
    """
    创建月度比赛
    """
    form = MonthlyCompetitionForm()
    if form.validate_on_submit():
        MonthlyCompetitionController.create_competition(
            name=form.name.data,
            description=form.description.data,
            start_date=form.start_date.data,
            end_date=form.end_date.data
        )
        flash('月度比赛创建成功', 'success')
        return redirect(url_for('student_reservations.monthly_competitions'))
    return render_template('student_reservations/create_monthly_competition.html', form=form)


@student_reservations_bp.route('/')
@login_required
@role_required('student', 'super_admin', 'campus_admin')
def index():
    """
    学员预约列表页面

    显示学员的所有预约，支持筛选和分页
    管理员可以通过user_id参数查看指定用户的预约
    """
    # 确定要查看的用户ID
    user_id = request.args.get('user_id', type=int)

    # 权限检查
    if current_user.is_student():
        # 学员只能查看自己的预约
        target_user_id = current_user.id
        if user_id and user_id != current_user.id:
            flash('您只能查看自己的预约记录', 'error')
            return redirect(url_for('student_reservations.index'))
    elif current_user.is_super_admin() or current_user.is_campus_admin():
        # 管理员可以查看指定用户的预约，如果没有指定则查看自己的
        if user_id:
            target_user_id = user_id
            # 验证用户是否存在
            from app.models.user import User
            target_user = User.query.get(user_id)
            if not target_user:
                flash('指定的用户不存在', 'error')
                return redirect(url_for('dashboard.index'))
        else:
            target_user_id = current_user.id
    else:
        flash('您没有权限访问此功能', 'error')
        return redirect(url_for('dashboard.index'))

    # 创建筛选表单
    filter_form = ReservationFilterForm(student_id=target_user_id)

    # 获取筛选参数
    status = request.args.get('status', '')
    start_date = None
    end_date = None
    coach_id = request.args.get('coach_id', '')
    page = request.args.get('page', 1, type=int)

    # 解析日期参数
    if request.args.get('start_date'):
        try:
            start_date = datetime.strptime(request.args.get('start_date'), '%Y-%m-%d').date()
        except ValueError:
            pass

    if request.args.get('end_date'):
        try:
            end_date = datetime.strptime(request.args.get('end_date'), '%Y-%m-%d').date()
        except ValueError:
            pass

    # 获取预约列表
    result = ReservationController.get_student_reservations(
        student_id=target_user_id,
        status=status if status else None,
        start_date=start_date,
        end_date=end_date,
        page=page,
        per_page=10
    )

    if not result['success']:
        flash(result['message'], 'error')
        reservations = []
        pagination = None
    else:
        reservations = result['data']['reservations']
        pagination = result['data']['pagination']

    # 获取统计数据
    stats_result = ReservationController.get_student_statistics(target_user_id)
    statistics = stats_result['data'] if stats_result['success'] else {}

    # 获取目标用户信息（用于页面显示）
    from app.models.user import User
    target_user = User.query.get(target_user_id) if target_user_id != current_user.id else current_user

    # 设置表单的默认值
    if request.method == 'GET':
        filter_form.status.data = status
        filter_form.start_date.data = start_date
        filter_form.end_date.data = end_date
        filter_form.coach_id.data = coach_id

    return render_template('student_reservations/index.html',
                         reservations=reservations,
                         pagination=pagination,
                         filter_form=filter_form,
                         statistics=statistics,
                         target_user=target_user,
                         filter_params={
                             'status': status,
                             'start_date': start_date,
                             'end_date': end_date,
                             'coach_id': coach_id,
                             'user_id': target_user_id if target_user_id != current_user.id else None
                         })


@student_reservations_bp.route('/create', methods=['GET', 'POST'])
@login_required
@student_required
def create():
    """
    创建预约页面
    """
    form = CreateReservationForm(
        student_id=current_user.id,
        campus_id=current_user.campus_id
    )

    print(f"DEBUG: Create view - request method: {request.method}")

    if request.method == 'POST':
        print(f"DEBUG: POST data received:")
        print(f"  coach_id: {form.coach_id.data}")
        print(f"  table_id: {form.table_id.data}")
        print(f"  reservation_date: {form.reservation_date.data}")
        print(f"  start_time: {form.start_time.data}")
        print(f"  end_time: {form.end_time.data}")
        print(f"  form.validate_on_submit(): {form.validate_on_submit()}")

        if form.errors:
            print(f"DEBUG: 表单验证错误: {form.errors}")

    if form.validate_on_submit():
        result = ReservationController.create_reservation(
            student_id=current_user.id,
            coach_id=int(form.coach_id.data),
            table_id=int(form.table_id.data),
            reservation_date=form.reservation_date.data,
            start_time=form.start_time.data,
            end_time=form.end_time.data
        )

        if result['success']:
            flash('预约创建成功！', 'success')
            return redirect(url_for('student_reservations.detail',
                                  reservation_id=result['data']['reservation_id']))
        else:
            flash(result['message'], 'error')
    else:
        if request.method == 'POST':
            print("DEBUG: 表单验证失败，返回表单页面")

    return render_template('student_reservations/create.html', form=form)


@student_reservations_bp.route('/detail/<int:reservation_id>')
@login_required
@student_required
def detail(reservation_id):
    """
    预约详情页面
    """
    result = ReservationController.get_reservation_detail(
        reservation_id=reservation_id,
        user_id=current_user.id
    )

    if not result['success']:
        flash(result['message'], 'error')
        return redirect(url_for('student_reservations.index'))

    reservation_data = result['data']
    return render_template('student_reservations/detail.html',
                         reservation_data=reservation_data)


@student_reservations_bp.route('/edit/<int:reservation_id>', methods=['GET', 'POST'])
@login_required
@student_required
def edit(reservation_id):
    """
    修改预约页面
    """
    # 获取预约详情
    detail_result = ReservationController.get_reservation_detail(
        reservation_id=reservation_id,
        user_id=current_user.id
    )

    if not detail_result['success']:
        flash(detail_result['message'], 'error')
        return redirect(url_for('student_reservations.index'))

    reservation = detail_result['data']['reservation']

    # 检查是否可以修改
    if reservation.status != 'pending':
        flash('只能修改待确认的预约', 'error')
        return redirect(url_for('student_reservations.detail', reservation_id=reservation_id))

    if not reservation.can_be_cancelled():  # 使用相同的时间限制
        flash('预约开始前24小时内不能修改', 'error')
        return redirect(url_for('student_reservations.detail', reservation_id=reservation_id))

    form = EditReservationForm(
        reservation=reservation,
        campus_id=current_user.campus_id
    )

    if form.validate_on_submit():
        result = ReservationController.update_reservation(
            reservation_id=reservation_id,
            user_id=current_user.id,
            reservation_date=form.reservation_date.data,
            start_time=form.start_time.data,
            end_time=form.end_time.data,
            table_id=int(form.table_id.data)
        )

        if result['success']:
            flash('预约修改成功！', 'success')
            return redirect(url_for('student_reservations.detail',
                                  reservation_id=reservation_id))
        else:
            flash(result['message'], 'error')

    return render_template('student_reservations/edit.html',
                         form=form, reservation=reservation)


@student_reservations_bp.route('/cancel/<int:reservation_id>', methods=['GET', 'POST'])
@login_required
@student_required
def cancel(reservation_id):
    """
    取消预约页面
    """
    # 获取预约详情
    detail_result = ReservationController.get_reservation_detail(
        reservation_id=reservation_id,
        user_id=current_user.id
    )

    if not detail_result['success']:
        flash(detail_result['message'], 'error')
        return redirect(url_for('student_reservations.index'))

    reservation = detail_result['data']['reservation']

    # 检查是否可以取消
    if not reservation.can_be_cancelled():
        flash('该预约无法取消', 'error')
        return redirect(url_for('student_reservations.detail', reservation_id=reservation_id))

    form = CancelReservationForm()

    if form.validate_on_submit():
        # 构建取消原因
        reason = form.get_reason_display()
        if form.additional_notes.data:
            reason += f"：{form.additional_notes.data}"

        result = ReservationController.cancel_reservation(
            reservation_id=reservation_id,
            user_id=current_user.id,
            reason=reason
        )

        if result['success']:
            flash('预约取消成功', 'success')
            return redirect(url_for('student_reservations.index'))
        else:
            flash(result['message'], 'error')

    return render_template('student_reservations/cancel.html',
                         form=form, reservation=reservation)


@student_reservations_bp.route('/calendar')
@login_required
@student_required
def calendar():
    """
    预约日历视图
    """
    # 获取年月参数
    year = request.args.get('year', datetime.now().year, type=int)
    month = request.args.get('month', datetime.now().month, type=int)

    # 获取日历数据
    result = ReservationController.get_calendar_data(
        student_id=current_user.id,
        year=year,
        month=month
    )

    if not result['success']:
        flash(result['message'], 'error')
        calendar_data = {}
    else:
        calendar_data = result['data']['calendar_data']

    # 计算日历显示信息
    current_date = date(year, month, 1)
    prev_month = current_date - timedelta(days=1)
    next_month = current_date.replace(day=28) + timedelta(days=4)
    next_month = next_month.replace(day=1)

    return render_template('student_reservations/calendar.html',
                         calendar_data=calendar_data,
                         current_year=year,
                         current_month=month,
                         prev_year=prev_month.year,
                         prev_month=prev_month.month,
                         next_year=next_month.year,
                         next_month=next_month.month)


# API 接口

@student_reservations_bp.route('/api/available-tables')
@login_required
@student_required
def api_available_tables():
    """
    API：获取可用球台列表
    """
    try:
        date_str = request.args.get('date')
        start_time_str = request.args.get('start_time')
        end_time_str = request.args.get('end_time')

        if not all([date_str, start_time_str, end_time_str]):
            return jsonify({
                'success': False,
                'message': '缺少必要参数'
            }), 400

        # 验证当前用户是否有校区信息
        if not current_user.campus_id:
            return jsonify({
                'success': False,
                'message': '用户校区信息缺失，请联系管理员'
            }), 400

        # 解析时间参数
        reservation_date = datetime.strptime(date_str, '%Y-%m-%d').date()
        start_time = datetime.strptime(start_time_str, '%H:%M').time()
        end_time = datetime.strptime(end_time_str, '%H:%M').time()

        # 获取可用球台
        result = ReservationController.get_available_tables(
            campus_id=current_user.campus_id,
            reservation_date=reservation_date,
            start_time=start_time,
            end_time=end_time
        )

        if result['success']:
            tables_data = [
                {
                    'id': table.id,
                    'name': table.name,
                    'status_display': table.get_status_display()
                }
                for table in result['data']['tables']
            ]
            return jsonify({
                'success': True,
                'data': {'tables': tables_data}
            })
        else:
            return jsonify(result)

    except ValueError as e:
        return jsonify({
            'success': False,
            'message': '日期或时间格式错误'
        }), 400
    except Exception as e:
        current_app.logger.error(f"获取可用球台失败: {str(e)}")
        return jsonify({
            'success': False,
            'message': '获取球台信息失败，请稍后重试'
        }), 500


@student_reservations_bp.route('/api/time-slots')
@login_required
@student_required
def api_time_slots():
    """
    API：获取可用时间段
    """
    date_str = request.args.get('date')
    coach_id = request.args.get('coach_id')

    if not all([date_str, coach_id]):
        return jsonify({
            'success': False,
            'message': '缺少必要参数'
        })

    try:
        reservation_date = datetime.strptime(date_str, '%Y-%m-%d').date()

        # 生成时间段选项（8:00-22:00，每30分钟一个时间段）
        time_slots = []
        current_time = datetime.combine(reservation_date, datetime.min.time().replace(hour=8))
        end_time = datetime.combine(reservation_date, datetime.min.time().replace(hour=22))

        while current_time < end_time:
            time_slots.append({
                'time': current_time.time().strftime('%H:%M'),
                'display': current_time.time().strftime('%H:%M')
            })
            current_time += timedelta(minutes=30)

        return jsonify({
            'success': True,
            'data': {'time_slots': time_slots}
        })

    except ValueError:
        return jsonify({
            'success': False,
            'message': '日期格式错误'
        })


@student_reservations_bp.route('/api/reservation/<int:reservation_id>/quick-cancel', methods=['POST'])
@login_required
@student_required
def api_quick_cancel(reservation_id):
    """
    API：快速取消预约
    """
    reason = request.json.get('reason', '学员取消')

    result = ReservationController.cancel_reservation(
        reservation_id=reservation_id,
        user_id=current_user.id,
        reason=reason
    )

    return jsonify(result)


@student_reservations_bp.route('/api/statistics')
@login_required
@student_required
def api_statistics():
    """
    API：获取学员预约统计
    """
    result = ReservationController.get_student_statistics(current_user.id)
    return jsonify(result)


@student_reservations_bp.route('/api/upcoming')
@login_required
@student_required
def api_upcoming():
    """
    API：获取即将到来的预约
    """
    result = ReservationController.get_student_reservations(
        student_id=current_user.id,
        status='confirmed',
        start_date=date.today(),
        page=1,
        per_page=5
    )

    if result['success']:
        upcoming_reservations = [
            reservation for reservation in result['data']['reservations']
            if reservation.is_upcoming()
        ]
        return jsonify({
            'success': True,
            'data': {'reservations': upcoming_reservations}
        })
    else:
        return jsonify(result)


@student_reservations_bp.route('/api/calculate-fee')
@login_required
@student_required
def api_calculate_fee():
    """
    API：计算预约费用和余额验证
    """
    try:
        # 获取参数
        coach_id = request.args.get('coach_id', type=int)
        table_id = request.args.get('table_id', type=int)
        duration = request.args.get('duration', type=int)

        if not all([coach_id, table_id, duration]):
            return jsonify({
                'success': False,
                'message': '参数不完整'
            }), 400

        # 获取教练信息（从users表查询）
        from app.models.user import User
        coach = User.query.filter_by(id=coach_id, role='coach', status='active').first()

        if not coach:
            return jsonify({
                'success': False,
                'message': '教练不存在或不可用'
            }), 404

        # 获取球台信息
        from app.models.table import Table
        table = Table.query.filter_by(id=table_id, status='available').first()

        if not table:
            return jsonify({
                'success': False,
                'message': '球台不存在或不可用'
            }), 404

        # 验证球台是否属于当前用户的校区
        if table.campus_id != current_user.campus_id:
            return jsonify({
                'success': False,
                'message': '球台不属于您的校区'
            }), 400

        # 计算费用（根据数据库结构）
        from decimal import Decimal
        hours = Decimal(duration) / 60  # 将分钟转换为小时

        # 教练课时费（从users表的hourly_rate字段）
        hourly_rate = coach.hourly_rate if coach.hourly_rate else Decimal('100')
        course_fee = hourly_rate * hours

        # 球台费用（暂时设为0，可根据需求调整）
        table_fee = Decimal('0')

        # 总费用
        total_fee = course_fee + table_fee

        # 获取当前用户余额（从user_accounts表）
        from app.models.account import UserAccount
        user_account = UserAccount.query.filter_by(user_id=current_user.id).first()
        current_balance = user_account.balance if user_account else Decimal('0')

        # 检查余额是否足够
        balance_sufficient = current_balance >= total_fee

        return jsonify({
            'success': True,
            'data': {
                'course_fee': float(course_fee),  # 课程费
                'table_fee': float(table_fee),    # 球台费
                'total_fee': float(total_fee),    # 总费用
                'hourly_rate': float(hourly_rate),
                'duration_hours': float(hours),
                'current_balance': float(current_balance),
                'balance_sufficient': balance_sufficient,
                'coach_name': coach.real_name,
                'table_name': table.name,
                'campus_name': table.campus.name if table.campus else ''
            }
        })

    except Exception as e:
        current_app.logger.error(f"计算费用失败: {str(e)}")
        return jsonify({
            'success': False,
            'message': '计算费用失败，请稍后重试'
        }), 500